import './public-path'
import { createApp } from 'vue'
import App from './App.vue'
import subApp from './subApp.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import Antd from 'ant-design-vue'
import 'lib-styles/ant-design-theme.less'
import 'lib-styles/ovveride.css'
import 'lib-styles/transition.less'
import 'lib-assets/fonts/iconfont.css'
import globalRegister from './globalRegister'
import { deepClone } from 'lib-utils'

let instance: any = null

function render(props: any = {}) {
  const { container } = props
  // 设置插件
  if (props) {
    let prevState = deepClone(store.state)
    // 当store初始化后调用
    store.subscribe((mutation, state) => {
      // 每次 mutation 之后调用
      const nextState = deepClone(state)
      if (JSON.stringify(nextState) !== JSON.stringify(prevState)) {
        prevState = nextState
        // 微应用中store变更后，将状态更新到主应用
        props.setGlobalState &&
          props.setGlobalState({ ...state.common })
      }
    })

    // 主应用状态发生变化后，自动同步到微应用
    props.onGlobalStateChange &&
      props.onGlobalStateChange(
        (state, prev) => {
          store.commit('initCommonStore', state)
        }, true
      )
  }
  // qiankun时作为子应用嵌入，不包含菜单栏和头部。单独运行时布局与主应用相同
  if (!(window as any).__POWERED_BY_QIANKUN__) {
    instance = createApp(App)
  } else {
    instance = createApp(subApp)
  }
  instance
    .use(Antd)
    .use(store)
    .use(router)
    .use(globalRegister)
    .mount(container ? container.querySelector('#app') : '#app')
}

if (!(window as any).__POWERED_BY_QIANKUN__) {
  render()
}

export async function bootstrap() {
  console.log('%c ', 'color: green;', 'vue3.0 app bootstraped')
}


export async function unmount() {
  instance.unmount();
  instance._container.innerHTML = ''
  instance = null
}

/**
 * 应用每次进入都会调用 mount 方法，通常我们在这里触发应用的渲染方法
 */
export async function mount(props) {
  render(props)
}
